package com.hamizhong.iflowers.db.dao.base;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * 所有HibernateDao的基类,默认实现了最基本的增删改查方法
 * @author ZhongJiang
 *
 * @param <T>
 * @param <PK>
 */
public abstract class MyBaseHibernateDao<T, PK extends Serializable> extends HibernateDaoSupport implements MyBaseDao<T, PK>{
	
//	MyLogger logger = MyLoggerFactory.getLogger(this.getClass());
	
	private Class<T> entityPOJO;
	
	public MyBaseHibernateDao() {
		Type type = getClass().getGenericSuperclass();
		Type trueType = ((ParameterizedType) type).getActualTypeArguments()[0];
		this.entityPOJO = (Class<T>) trueType;
	}
	
	public PK add(T t) {
		return (PK) this.getHibernateTemplate().save(t);
	};
	
	public void update(T t) {
		this.getHibernateTemplate().update(t);
	};
	
/*	public void deleteById(PK id) {
		this.getHibernateTemplate().delete(id);
	};*/
	
	public void delete(T t) {
		this.getHibernateTemplate().delete(t);
	}
	
	public T findById(PK id) {
		return this.getHibernateTemplate().get(entityPOJO, id);
	};
	
	public List<T> findAll() {
		return this.getHibernateTemplate().loadAll(entityPOJO);
	}
	
	public List<T> findByExample(HashMap<String, Object> param) {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entityPOJO);
		Iterator it = param.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			Object value = param.get(key);
			detachedCriteria.add(Restrictions.eq(key, value));
		}
		List<T> rs = this.getHibernateTemplate().findByCriteria(detachedCriteria);
		if(rs == null) {
			rs = new ArrayList<T>();
		}
		return rs;
	}
}
